<template>
  <layout-slot v-cloak bodyImage="" class="article-main" class-name="article-content">

    <!-- 非移动端展示 -->
    <div class="post-header-thumb  bg-orange"
         :style="{backgroundImage:`url(${articleDetail.src})`}">
      <div class="post-header-thumb-op"
           :style="{backgroundImage:`url(${articleDetail.src})`}"></div>
      <div class="post-header-thumb-cover">
        <div class="post-header-thumb-container">
          <div class="post-header-thumb-title">
            {{ articleDetail.title }}
          </div>
          <div class="post-header-thumb-meta">

            <time datetime="2021-04-04T16:09:00+08:00" itemprop="datePublished">
              <i class="fa fa-clock-o" aria-hidden="true"> </i>
              {{ articleDetail.time | dateFormat('{y}-{m}-{d}') }}
            </time>
            <span v-html="'&nbsp;&nbsp;&nbsp;'"></span>
            <i class="fa fa-tags" aria-hidden="true"></i>
            <router-link v-if="articleDetail.category" :to="articleDetail.category.url">{{ articleDetail.category.title
              }}
            </router-link>
            <span v-html="'&nbsp;&nbsp;&nbsp;'"></span>
            <i class="fa fa-comments-o" aria-hidden="true"></i>
            <a v-if="articleDetail.comments" href="#comments">
              {{ articleDetail.comments.number }} {{ $t('comments') }}
            </a>&nbsp;&nbsp;
            <span v-html="'&nbsp;&nbsp;&nbsp;'"></span>
            <i class="fa fa-eye" aria-hidden="true"></i>
            {{ articleDetail.views }} {{ $t('views') }}
          </div>
          <div class="post-tags">
            <router-link :key="index" v-for="(item,index) of articleDetail.tags" :to="item.url">
              {{ item.name }}
            </router-link>
          </div>
        </div>
      </div>
    </div>
    <!-- 文章主体 -->
    <article ref="article_body" class="main-content post-page" itemscope="" itemtype="http://schema.org/Article">

      <!-- mobile -->
      <div class="post-header">
        <h1 class="post-title" itemprop="name headline">{{ articleDetail.title }}</h1>
        <div class="post-data">
          <time datetime="2021-04-04T16:09:00+08:00" itemprop="datePublished"><i class="fa fa-clock-o"
                                                                                 aria-hidden="true"> </i> {{
            articleDetail.time | dateFormat('{y}-{m}-{d}') }}
          </time>&nbsp;&nbsp;
          <i v-if="articleDetail.category" class="fa fa-tags" aria-hidden="true"></i>
          <router-link
            :to="articleDetail.category.url">{{
            articleDetail.category.title }}
          </router-link>&nbsp;&nbsp;
          <i class="fa fa-comments-o" aria-hidden="true"></i>
          <a v-if="articleDetail.comments" href="#comments"> {{ articleDetail.comments.number }} {{ $t('comments')
            }}</a>&nbsp;&nbsp;
          <i class="fa fa-eye" aria-hidden="true"></i>
          {{ articleDetail.views }} {{ $t('views') }}
        </div>
      </div>

      <div id="post-content" class="post-content" itemprop="articleBody">
        <p class="post-tags">
          <router-link :key="index" v-for="(item,index) of articleDetail.tags" :to="item.url">{{ item.name }}
          </router-link>
        </p>
        <div class="protected" ref="article_main" v-if="articleDetail.auth === 0">
          <p class="word">访问验证码漪悼遛，进不去请点击<b> 关于 </b>联系站长获取。</p>
          <p><input v-model="password" type="text" class="text" name="protectPassword" @keyup.enter="articleByPass">
            <span v-html="'&nbsp;&nbsp;&nbsp;'"></span>
            <input type="button" class="submit" value="提交" @click="articleByPass"></p>
        </div>
        <!-- body start -->
        <div v-else ref="article_main" v-html="articleDetail.body"></div>
        <!-- body end -->
      </div>
      <p class="post-info">
      </p>
      <div style="text-align: center;">
      <span
        v-if="articleDetail.footerStatement"
        v-html=
          "$t('statement')
          .replace('XXX',articleDetail.footerStatement.url)
          .replace('YYY',articleDetail.footerStatement.name)
          .replace('ZZZ',$util.parseTime(articleDetail.footerStatement.updateTime))"
      ></span>
        如果你觉得我的文章不错，不妨鼓励我继续写作。
      </div>
      <div id="rewardButton"
           style="padding: 10px 0; margin: 20px auto; width: 100%; font-size:16px; text-align: center;">
        <div id="reward-qr-code" style="padding: 50px;background-color: #393D49; color: #fff;display: none;"><img
          style="width: 100%;" src="https://rawchen.com/qrcode.jpg"></div>
        <button type="button" @click="showSupportModal  = true">支持</button>
      </div>
      <p></p>

      <div class="post-next-prev">
        <div class="padd">
          <!-- 上一篇 -->
          <div class="next-prev" v-if="neighborArticle[1]">
            <a :href="'/article-detail/'+neighborArticle[1].id" :title="neighborArticle[1].title">
              <div class="card">
                <div class="card-img">
                  <img :src="neighborArticle[1].image" :alt="neighborArticle[1].title">
                  <div class="overlay"></div>
                </div>
                <div class="card-body">
                  <h2 class="card-title">{{neighborArticle[1].title}}</h2>
                  <div class="card-footer">

                    <i class="fa fa-angle-left"></i><span>上一篇</span>
                  </div>
                </div>
              </div>
            </a>
          </div>

          <!-- 下一篇 -->
          <div class="next-prev" v-if="neighborArticle[0]">
            <a :href="'/article-detail/'+neighborArticle[0].id" :title="neighborArticle[0].title">
              <div class="card">
                <div class="card-img">
                  <img :src="neighborArticle[0].image" :alt="neighborArticle[0].title">
                  <div class="overlay"></div>
                </div>
                <div class="card-body">
                  <h2 class="card-title">{{neighborArticle[0].title}}</h2>
                  <div class="card-footer">
                    <span>下一篇</span>
                    <i class="fa fa-angle-right"></i>
                  </div>
                </div>
              </div>
            </a>
          </div>

        </div>
      </div>
    </article>


    <!-- 评论系统 -->

    <message/>


    <!-- 目录 -->
    <div v-show="Object.keys(outline).length > 0" ref="outline" id="directory-content"
         class="directory-content initial  unpinned" :class="{'mobile-dir':showMobileDir}" @click="showMobileDir = false">
      <div id="directory" class="clearfix">
        <ul>
          <li v-for="(item,i) of outline">
            <a @click="anchorPoint(item.id)" href="javascript:">{{ (i + 1) + ' ' + item.id }}</a>
            <ul v-if="item.children && item.children.length > 0">
              <li v-for="(tmp,j) of item.children">
                <a @click="anchorPoint(tmp.id)" href="javascript:">{{ (i + 1) + '.' + (j + 1) + ' ' + tmp.id }}</a>
                <ul v-if="tmp.children && tmp.children.length > 0">
                  <li v-for="(m,n) of tmp.children">
                    <a @click="anchorPoint(m.id)" href="javascript:">{{ (i + 1) + '.' + (j + 1) + '.' + (n + 1) + ' ' +
                      m.id }}</a>
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>

    <!-- 图片的viewer -->
    <!-- <canvas id="evanyou-canvas"  style="position: fixed; top: 0; left: 0; z-index:-1; width: 100%; pointer-events: none;"></canvas> -->

    <!-- 支持的review -->
<!--    <transition name="fade">-->
<!--      <div v-show="showSupportModal" class="wrap" @click="showSupportModal = false"></div>-->
<!--    </transition>-->

    <!-- 移动端目录 -->
    <a v-show="Object.keys(outline).length > 0" @click.stop="showMobileDir = true" class="mobile-directory" href="javascript:">
      <i class="fas fa-list-ul"></i>
    </a>

  </layout-slot>
</template>

<script>
  import LayoutSlot from "./slot/layout-slot";
  import settings from "../../../settings";
  import Message from "@/components/Twikoo";
  import {getArticleById, recordCount} from "@/api/home";

  import VditorPreview from 'vditor/dist/method.min'


  // import hljs from 'highlight.js'
  // import 'highlight.js/styles/monokai.css'

  import {Fancybox} from "@fancyapps/ui";
  import "@fancyapps/ui/dist/fancybox.css";

  import Cookies from 'js-cookie'
  import ImageSlot from "@/views/skins/GreenBook/slot/image-slot";
  import {canvasDraw, evanyou, listToTree} from "@/utils/utils";

  export default {
    name: "vue-article",
    components: {Message, LayoutSlot},
    props: {
      id: [Number, String]
    },
    beforeRouteEnter(to, from, next) {

      next()
    },
    data() {
      return {
        articleDetail: {
          comments: {},
          footerStatement: {
            name: "-"
          },
          category: {
            url: ""
          },
          auth: ""
        },
        outline: [],
        password: "",
        neighborArticle: [],
        showSupportModal: false,
        showMobileDir:false
      }
    },
    mounted() {

      new Headroom(this.$refs.outline, {
        offset: this.$refs.article_body.offsetTop,
        tolerance: 0,
        classes: {initial: "headroom", pinned: "slideDown", unpinned: "slideUp"}
      }).init();

      let pass = Cookies.get('ARTICLE__pASS' + this.id)

      if (pass) {
        this.password = window.atob(pass)
      }
      this.getArticleDetail()

      evanyou()

      this.recordView()
      // Prism.plugins.toolbar.hook({element:document.body})
      canvasDraw()
    },
    beforeDestroy() {
      let canvas = document.getElementById('bgCanvas')
      canvas.remove()
    },
    methods: {
      recordView() {
        recordCount({id: this.id}).then((res) => {
        })
      },
      articleByPass() {
        this.getArticleDetail()
      },
      previewOutline() {
        const initOutline = () => {
          const headingElements = []
          Array.from(this.$refs.article_main.children).forEach((item) => {
            if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
              headingElements.push(item)
            }
          })
        }
        initOutline()
      },
      anchorPoint(id) {
        let base = document.getElementsByClassName('main-content')[0].offsetTop
        let target = document.getElementById(id)

        if (target) {
          window.scrollTo({
            top: target.offsetTop + base,
            behavior: "smooth"
          })
        }
        this.$router.push(`${this.$route.path}#${id}`)
      },
      getCatalog(textHtml) {
        let converter = document.createElement("DIV")
        converter.innerHTML = textHtml

        let elements = converter.getElementsByTagName('*')
        let html = `<ul level="1">`, serial = 0, flag = 0, num = {}, serial1 = 0, hr = [], hash = {}, tocHTML = ""
        for (let i = 0; i < elements.length; i++) {
          let item = elements[i]
          if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
            let id = item.getAttribute('id')
            let h_serial = item.tagName.substr(1, 1)
            if (h_serial == 1) {
              serial++
              serial1 = 0
              num[serial] = {
                inner: `${serial} ${item.innerText.replace(/\s/g, "")}`,
                children: [],
                id: item.innerText.replace(/\s/g, "")
              }
            } else if (h_serial == 2) {
              serial1++
              if (num[serial]) {
                num[serial].children.push({
                  inner: `${serial}.${serial1} ${item.innerText.replace(/\s/g, "")}`,
                  children: [],
                  id: item.innerText.replace(/\s/g, "")
                })
              }
            } else if (h_serial == 3) {

            }
            // 构造树形结构的数据
            this.makeTreeData(Number(h_serial), hr, id, hash)
          }
        }
        // console.log(hr)
        hr = listToTree(hr, 'id', 'pid')
        // console.log(hr)
        return hr
      },
      makeTreeData(h_serial, hr, id, hash) {

        let pid = id, key = `h${h_serial}`, keyLast = `h${Number(h_serial) + 1}`
        if (h_serial === 1) {
          pid = ''
        } else {
          if (!hash[key] && hr[hr.length - 1]) {
            hash[key] = hr[hr.length - 1]
          }
          if (hash[key] && hash[key].h_serial != h_serial) {
            pid = hash[key].id
          } else {
            pid = ''
          }
        }
        hash[keyLast] = ''


        hr.push({
          h_serial,
          id,
          pid: pid,
        })

      },
      getArticleDetail() {
        this.$store.commit("setLoading", true)
        let params = {
          id: this.id
        }
        if (this.password) {
          params.password = this.password
        }
        getArticleById(params).then(({data}) => {



          if (data.code === 200) {
            this.neighborArticle = data.neighborArticle
            let article = data.data




            this.articleDetail = {
              isTop: true,
              color: settings.textColors[1],
              url: `/article-detail/${article.oId}`,//item.articlePermalink,
              src: article.articleImg1URL,
              title: article.articleTitle,
              Topping: true,
              time: article.articleCreated,
              category: {title: article.categoryTitle, url: "/category/" + article.categoryURI},
              comments: {number: article.articleCommentCount, url: "/"},
              views: ++article.articleViewCount,
              abstract: "购买地址：腾讯云：[https://cloud.tencent.com/act/cps/redirect?redirect=1575&amp;cps_key=b58209dca42a9decdae2f276d61acd77&amp;from=console)阿里云：https://www.aliyun.com",
              tags: article.articleTags.split(",").map(item => ({
                name: item,
                url: "/tag/" + item
              })),
              body: article.articleContent,
              auth: article.auth,
              footerStatement: {
                updateTime: article.articleUpdated,
                name: "zipfang"
              }
            }

            this.$util.getCommentsCount([`/article-detail/${article.oId}`]).then((res)=>{
              if(Array.isArray(res)) {
                this.articleDetail.comments = {
                  number: res[0].count,
                  url: res[0].url
                }
              }
            })

            if (this.$refs.article_main && article.articleContent) {
              this.outline = this.getCatalog(article.articleContent)


              // render start

              VditorPreview.preview(this.$refs.article_main, article.articleContent, {
                hljs: {
                  enable: true,
                  style: "monokai",
                  lineNumber: true
                },
                after: () => {
                  if (this.$route.hash) {
                    this.anchorPoint(decodeURIComponent(this.$route.hash.replace("#", "")))
                  }
                  // 代码样式重制
                  let codes = document.getElementsByTagName('code')
                  if (codes && codes.length > 0) {
                    for (let el of codes) {
                      if (el) {
                        let previous = el.parentElement
                        let codeType = document.createElement('div')
                        codeType.classList.add("code-type")
                        if (el.classList[0]) {
                          codeType.innerText = el.classList[0].split('-')[1]
                        }
                        if (previous) {
                          previous.appendChild(codeType)
                        }
                      }
                    }
                  }

//https://fancyapps.com/docs/ui/fancybox/options
                  Fancybox.bind(".post-content img", {
                    // Your options go here
                    groupAll: true
                  });
                  let images = document.querySelectorAll('.post-content img')
                  images.forEach((el) => {
                    el.onerror = function (e) {
                      e.target.src = require("@/assets/images/error/load_failed.png")
                    }
                  })

                  this.$store.commit("setStoreValue",{
                    subTitle : article.articleTitle
                  })

                  //Skeleton Screen
                  this.$store.commit("setLoading", false)
                }
              })
              // render end
            }

            if (article.auth === 1) {
              Cookies.set('ARTICLE__pASS' + this.id, window.btoa(this.password), {
                expires: 7
              })

            }
            if (article.auth === 0) {
              this.$store.commit("setLoading", false)
            }
          }else{
            this.$router.push({name:"404"})
          }

        })
      },
    }

  }
  // http://www.ha97.com/4030.html
</script>
<!--<style src="./scss/okaikia.css"></style>-->
<style lang="scss" scoped>
  .article-main {

  }

  .post-page {
    background: hsla(0, 0%, 100%, .9);
  }



  // 针对整个文章的渲染
  .wrap{
    left: 50%;
    top: 50%;
    margin-top: -110px;
    margin-left: -110px;
    border-radius: 3px;
    position: fixed;
    width: 220px;
    height: 220px;
    overflow-y: auto;
    z-index: 1111;
    background: #f2f2f2;
    box-shadow: 1px 1px 20px 2px #888;
    transition: all .8s;
    &:hover{
      transform:  scale(1.4);
    }
  }

  /*.fade-enter-active,.fade-leave-active{*/
  /*  transition: all .8s;*/

  /*}*/

  /*.fade-enter, .fade-leave-to !* .fade-leave-active below version 2.1.8 *! {*/
  /*  opacity: 0;*/
  /*  transform:  scale(1.4);*/

  /*}*/

  //.con {
  //  transform: translateX(-50%, -50%) scale(0.8, 0.8);
  //  left: 50%;
  //  top: 50%;
  //  border-radius: 3px;
  //  position: fixed;
  //  width: 220px;
  //  height: 220px;
  //  overflow-y: auto;
  //  z-index: 1111;
  //  transition: all .3s;
  //  visibility: hidden;
  //  background: #f2f2f2;
  //  opacity: 0;
  //}
//
  //.show {
  //  transform: translateX(-50%, -50%) scale(1, 1);
  //  visibility: visible;
  //  opacity: 1;
  //
  //}
</style>
<style lang="scss">
  .article-content {
    max-width: 100%;
  }
</style>
